// miniprogram/pages/wechat/wechat.js
var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    pass: false,
    user_headpic: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
    userInfo:{
      nickName: '',
      avatarUrl: 'https://picx.zhimg.com/v2-6fa81c23e6156f2152fa425a0c3d0994.jpeg'
    }, 
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let time = this.generate();
    this.setData({
      time
    })
  },
  generate: function(){
    return Date.now();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log(app.globalData.openid);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: app.globalData.title,
      imageUrl: 'https://picx.zhimg.com/v2-e56d36fc76c48a9e8748ad9f5fa152ed.png',
      path: "/pages/index/index"
  };
  },
  bindNicknameReview: function (event) {
    console.log(event);
    let pass = event.detail.pass;

    this.setData({
      pass
    })
  },
  inputName(e) {
    console.log(e);
    this.setData({
      'userInfo.nickName': e.detail.value
    })
  },
  onChooseAvatar(e) {
    console.log(e)
    const {
      avatarUrl
    } = e.detail
    const that = this
    if (avatarUrl) {
      // wx.cropImage({
      //   src: avatarUrl,
      //   cropScale: '1:1',
      //   success(res) {
      // console.log(res) 
      wx.showLoading({
        title: '上传中',
        mask: true,
      })
      wx.cloud.uploadFile({
        cloudPath: Date.now().toString() + parseInt(Math.random() * 10000) + '.png',
        filePath: avatarUrl, // 文件路径
        success: res => {
          // get resource ID
          console.log(res.fileID)
          that.setData({
            'userInfo.avatarUrl': res.fileID
          })
          wx.showToast({
            title: '上传成功',
          })
        },
        fail: err => {
          // handle error
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          })
        }
      })

      //   }
      // })
    }

  },

  toGo: function(){
    setTimeout(() => {
      this.onGotUserInfo();
    }, 500);
  },
  onGotUserInfo: function() {
    let that = this;
        //允许
      
        let userInfo = this.data.userInfo;

        if(!this.data.pass || userInfo.nickName == ''){
          wx.showToast({
            title: '请填写微信昵称',
            icon: 'none'
          })
          return
        }

        app.globalData.userInfo = userInfo;


        
        this.update(userInfo);
        

  

  },
  update: function(userInfo) {
    // 调用云函数
    let that = this;
    wx.cloud.callFunction({
      name: 'update',
      data: {
        userInfo: userInfo
      }
    })
    .then(res => {
      console.log('[云函数] [update]: ', res)
      wx.setStorageSync('userinfo', userInfo)

      wx.showToast({
        title: '更新成功',
        icon: 'success',
        duration: 2000
      })
      setTimeout(() => {
        wx.navigateBack({
          delta: 1
        })
      }, 2000);

      
    }).catch(err => {
      console.error('[云函数] [update] 调用失败', err)
      wx.navigateTo({
        url: '../deployFunctions/deployFunctions',
      })
    })
  },

  _update: function(_id,userInfo){
    const db = wx.cloud.database();

    
    db.collection('users').doc(_id).update({
      // data 字段表示需新增的 JSON 数据
      data: {
        ...userInfo
      }
    })
    .then(res => {
      console.log(res)
      console.log('[数据库] [查询记录] 成功: ', res);

      wx.setStorageSync('userinfo', userInfo)

      wx.showToast({
        title: '更新成功',
        icon: 'success',
        duration: 2000
      })
      setTimeout(() => {
        wx.navigateBack({
          delta: 1
        })
      }, 2000);
      

      
    })
    .catch((err)=>{
      console.log(err)
  
    })
  },
  toKefu: function(){
    wx.navigateTo({
      url: '../kefu/kefu'
    });
  },
  goHome: function(){
    wx.switchTab({
      url: '../index/index'
    });
  }
})